import os
import sys
import psycopg2
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class AddIpWindow(QWidget):
    update_Signal=pyqtSignal(int)
    def __init__(self,sort_department,parent=None):
        super(AddIpWindow, self).__init__()
        self.sort_department=sort_department
        self.parent=parent
        self.setWindowTitle('添加ip')
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.main_layout=QVBoxLayout()
        self.main_layout.setSpacing(15)
        self.name_layout=QHBoxLayout()
        self.name_label=QLabel('姓名:')
        self.name_edit=QLineEdit()
        self.name_layout.addWidget(self.name_label)
        self.name_layout.addWidget(self.name_edit)
        self.ip_layout=QHBoxLayout()
        self.ip_label=QLabel(' ip :')
        self.ip_edit=QLineEdit()
        self.ip_layout.addWidget(self.ip_label)
        self.ip_layout.addWidget(self.ip_edit)
        self.department_layout=QHBoxLayout()
        self.department_label=QLabel('部门:')
        self.department_comb=QComboBox()
        self.init_department(sort_department)
        self.department_layout.addWidget(self.department_label)
        self.department_layout.addWidget(self.department_comb)
        self.note_layout=QHBoxLayout()
        self.note_label=QLabel('备注:')
        self.note_text=QTextEdit()
        self.note_text.setMaximumHeight(80)
        self.note_layout.addWidget(self.note_label)
        self.note_layout.addWidget(self.note_text)
        self.btn_layout=QHBoxLayout()
        self.btn_layout.setSpacing(15)
        self.OK_btn=QPushButton('添加')
        self.OK_btn.clicked.connect(self._add_ip)
        self.No_btn=QPushButton('取消')
        self.btn_layout.addWidget(self.OK_btn)
        self.btn_layout.addWidget(self.No_btn)

        self.main_layout.addLayout(self.name_layout)
        self.main_layout.addLayout(self.ip_layout)
        self.main_layout.addLayout(self.department_layout)
        self.main_layout.addLayout(self.note_layout)
        self.main_layout.addLayout(self.btn_layout)
        self.setLayout(self.main_layout)

    def init_department(self,sort_department):
        deparment=sorted(sort_department.keys(),key=lambda x:sort_department[x])
        self.department_comb.addItems(deparment)

    def _add_ip(self):
        name=self.name_edit.text()
        ip=self.ip_edit.text()
        department=self.department_comb.currentText()
        note=self.note_text.toPlainText()
        if name and ip and department:
            sql="insert into account (artist,department,ip,note) values('{0}','{1}','{2}','{3}')".format(name,department,ip,note)
            time_connect, time_cur = self.parent._init_taskprogress_db()
            try:
                time_cur.execute(sql)
                time_connect.commit()
                self.update_Signal.emit(1)
            except Exception as _add_ip_ERR:
                print('_add_ip_ERR:',str(_add_ip_ERR))
            finally:
                time_connect.close()


class IPtable(QTableWidget):
    update_Signal=pyqtSignal(int)
    def __init__(self,sort_department,parent=None):
        super(IPtable, self).__init__()
        self.sort_department=sort_department
        self.parent=parent
        self.data_list=[]  #ip数据[(1, 'xx', '192.168.1.88', '12TD', None),(3, 'xx', '192.168.1.85', '12TD', None),...]
        self.setShowGrid(True)
        self.verticalHeader().setDefaultSectionSize(30)

        # self.verticalHeader().sectionDoubleClicked.connect(self.__v_set)
        self.horizontalHeader().setDefaultSectionSize(100)
        # self.horizontalHeader().sectionDoubleClicked.connect(self.__h_set)
        self.initAll()
        self.head_list=['索引','姓名','IP','部门','备注']
        self.setHorizontalHeaderLabels(self.head_list)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.rightMenu_Main)
        self.setEditTriggers(QAbstractItemView.DoubleClicked)
        # self.cellChanged.connect(self._cell_changed)

    def initAll(self):
        """
        初始化，让所有item不为None,初始化时没有表头，注意表头也不能空
        :return:
        """
        self.setColumnCount(5)
        self.setRowCount(5)
        # self.init_head()
        for r in range(self.rowCount()):
            for c in range(self.colorCount()):
                item=QTableWidgetItem()
                item.setText('')
                item.setBackground(QBrush(QColor('#F0FFFF')))
                item.setTextAlignment(Qt.AlignCenter)
                if c==0:
                    item.setFlags(Qt.NoItemFlags)
                self.setItem(r,c,item)

    def _cell_changed(self,row,column):
        print(row,column)
        db_id=self.item(row,0).text()
        name=self.item(row,1).text()
        ip=self.initAll(row,2).text()
        department=self.item(row,3).text()
        note=self.item(row,4).text()
        if db_id: #当存在id时，那么更新数据
            sql="update "



    def rightMenu_Main(self):
        all_indexes=self.selectionModel().selection().indexes()
        mainMenu = QMenu()
        deleteAction=QAction('删除',self)
        deleteAction.triggered.connect(self._delete_account)
        mainMenu.addAction(deleteAction)
        # c=-1
        # for i in all_indexes:
        #     c=i.column()

        # if c==1:
            # addAccountAction = QAction(u'删除', self)
            # addAccountAction.triggered.connect(self.addAccount)
            # mainMenu.addAction(addAccountAction)
            # addAccountAction = QAction(u'删除', self)
            # addAccountAction.triggered.connect(self.addAccount)
            # mainMenu.addAction(addAccountAction)


        # else:
        #     self.setEditTriggers(QAbstractItemView.editTriggers)

        #     addAccountAction=QAction(u'添加账号',self)
        #     addAccountAction.triggered.connect(self.addAccount)
        #     deleteAccountAction=QAction(u'删除此账号',self)
        #     deleteAccountAction.triggered.connect(self.deleteAccount)
        #     mainMenu.addAction(addAccountAction)
        #     mainMenu.addAction(deleteAccountAction)
        # if c==1:
        #     setShowNameAction=QAction('修改名称',self)
        #     setShowNameAction.triggered.connect(self.setShowName)
        #     mainMenu.addAction(setShowNameAction)
        #
        # if c==2:
        #     resetPasswordAction = QAction(u'清空密码', self)
        #     resetPasswordAction.triggered.connect(self.reset_password)
        #     mainMenu.addAction(resetPasswordAction)

        # if c==3:
        #     level_menu=QMenu('设置级别')
        #
        #     for p in self.p_level:
        #         p_action=QAction(p,self)
        #         level_menu.addAction(p_action)
        #     level_menu.triggered[QAction].connect(self.set_user_level)#[QAction]
        #     mainMenu.addMenu(level_menu)

        # if c==3:
        #
        #     for d in self.sort_department.keys():
        #         d_action=QAction(d,self)
        #         mainMenu.addAction(d_action)
        #     mainMenu.triggered[QAction].connect(self.setDepartment)

        mainMenu.exec_(QCursor.pos())

    def addAccount(self):
        cr=self.currentRow()
        print(cr)

    def _delete_account(self):
        # current_item=self.currentItem()
        row=self.currentRow()
        index_row=self.item(row,0)
        index_id=index_row.text()
        print('index_id:',index_id)
        sql = "delete from account where id={}".format(int(index_id))
        time_connect, time_cur = self.parent._init_taskprogress_db()
        try:
            time_cur.execute(sql)
            time_connect.commit()
            self.update_Signal.emit(1)
        except Exception as _delete_account_ERR:
            print('_delete_account_ERR:', str(_delete_account_ERR))
        finally:
            time_connect.close()



    def _add_row(self,int_value):
        """
        槽函数,返回选择的数量.根据数量在尾后添加空行数，注意设置垂直表头
        :param int_value:
        :return:
        """
        ori_count=self.rowCount()

        self.setRowCount(self.rowCount()+int_value)
        for r in range(ori_count,self.rowCount()):
            v_item=QTableWidgetItem()
            v_item.setText(str(r+1))
            self.setVerticalHeaderItem(r,v_item)
            for c in range(self.columnCount()):
                item=QTableWidgetItem()
                item.setText('')
                item.setBackground(QBrush(QColor('#F0FFFF')))
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(r,c,item)

    def setDepartment(self,departmentclass):

        text=departmentclass.text()
        current_item=self.currentItem()
        current_item.setText(text)



    def set_data(self,data_list):
        """
        设置data数据
        :param data_list:  [(1, 'xx', '192.168.1.88', '12TD', None),(3, 'xx', '192.168.1.85', '12TD', None),...]
        :return:
        """
        if data_list:
            self.data_list=data_list
            row_count=len(data_list)
            self.setRowCount(row_count)
            for r in range(row_count):
                for c in range(self.columnCount()):
                    content=data_list[r][c]
                    text=str(content) if content else ''
                    item=QTableWidgetItem()
                    item.setTextAlignment(Qt.AlignCenter)
                    item.setBackground(QBrush(QColor('#F0FFFF')))
                    item.setText(text)
                    self.setItem(r,c,item)


    def rightMenu(self):
        mainMenu=QMenu()
        mainMenu.exec_(QCursor.pos())



class IPwindow(QWidget):

    def __init__(self):
        super(IPwindow, self).__init__()
        self.sort_department={'01美术':1,'02模型':2,'03跟踪':3,'04动画':4,'05场景':5,'06灯光':6,'07特效一':7,'07特效二':8,
                                     '08合成一':9,'08合成二':10,'09包装':11,'10剪辑':12,'11调色':13,'12TD':14,'13虚拟':15,'14视效':16}

        self.btn_style = '''QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                  QPushButton{background-color:#D3D3D3}
                                  QPushButton{border:12px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:5px 13px}'''

        self.bitFont=QFont('',25,65)
        self.setWindowTitle('时光IP管理')
        self.setMinimumWidth(550)
        self.setMinimumHeight(800)
        self.main_layout=QVBoxLayout()
        self.show_label=QLabel('IP管理')
        self.show_label.setFont(self.bitFont)
        self.show_label.setAlignment(Qt.AlignCenter)
        self.tool_layout=QHBoxLayout()
        # self.import_btn=QPushButton('导入excel')
        self.import_btn=QPushButton('添加')
        self.import_btn.setStyleSheet(self.btn_style)
        self.import_btn.clicked.connect(self._open_add_ip)
        self.export_btn=QPushButton('导出excel')
        self.export_btn.setStyleSheet(self.btn_style)
        self.search_edit=QLineEdit()
        self.search_btn=QPushButton('筛选')
        self.search_btn.setStyleSheet(self.btn_style)
        self.search_btn.clicked.connect(self._filter)
        self.tool_layout.addWidget(self.import_btn)
        self.tool_layout.addWidget(self.export_btn)
        self.tool_layout.addWidget(self.search_edit)
        self.tool_layout.addWidget(self.search_btn)
        self.table=IPtable(self.sort_department,parent=self)
        self.table.update_Signal.connect(self.init_table)
        self.main_layout.addWidget(self.show_label)
        self.main_layout.addLayout(self.tool_layout)
        self.main_layout.addWidget(self.table)
        self.setLayout(self.main_layout)
        self.init_table()

    def init_table(self):
        ip_data=self.get_ip_data()
        if ip_data:
            self.table.set_data(ip_data)

    def _init_taskprogress_db(self):
        """
        创建一个操作本地_init_taskprogress_db数据库的临时连接
        :return:
        """
        try:
            time_connect = psycopg2.connect(database='taskprogress',
                                          user='timeaxis',
                                          password='timeaxis',
                                          host='192.168.1.222',
                                          port=5432)
            time_cursor = time_connect.cursor()
        except Exception as _init_taskprogress_db_ERR:
            print('_init_taskprogress_db_ERR:',str(_init_taskprogress_db_ERR))
            return None, None
        return time_connect, time_cursor

    def get_ip_data(self):
        data_list=[]
        time_connect, time_cur=self._init_taskprogress_db()
        sql="select id,artist,ip,department,note from account "
        try:
            time_cur.execute(sql)
            result=time_cur.fetchall()
            if result:
                for i in result:
                    print(i)
                    data_list.append(i)
        except Exception as get_ip_data_ERR:
            print('get_ip_data_ERR:',str(get_ip_data_ERR))
        finally:
            time_connect.close()
        return data_list

    def _open_add_ip(self):
        self.addipwindow = AddIpWindow(self.sort_department,parent=self)
        self.addipwindow.update_Signal.connect(self.init_table)
        self.addipwindow.show()


    def _filter(self):
        get_index=[]
        text=self.search_edit.text()
        if text:
            data_list=self.table.data_list
            for i in range(len(data_list)):
                # index=data_list[i][0]
                for content in data_list[i]:
                    if text in str(content):
                        if i not in get_index:
                            get_index.append(i)
            if get_index:
                for r in  range(self.table.rowCount()):
                    if r not in get_index:
                        self.table.hideRow(r)
        else:
            for r in range(self.table.rowCount()):
                self.table.showRow(r)
        print(get_index)


if __name__ == '__main__':
    app=QApplication(sys.argv)
    ipwindow=IPwindow()
    # ipwindow=AddIpWindow()

    ipwindow.show()
    sys.exit(app.exec_())